<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/7/4 下午3:44
 * +-------------------------------------------------------------
 */

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\Request;
use think\App;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;
use app\admin\model\Store as ModelStore;
use app\admin\validate\StoreValidate;
use think\response\Json;

/**
 * @ControllerAnnotation (title="加盟店管理")
 */
class Store extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model           = new ModelStore();
        $this->relationSearch  = true;
        $this->joinTable       = 'admin,owners,bank';
        $this->joinUpdateTable = 'admin,owners,bank';
        $this->validateClass   = StoreValidate::class;
    }

    /**
     * @NodeAnnotation (title="新增")
     * @param Request $request
     * @return Json
     */
    public function add(Request $request): Json
    {
        if(!$request->isPost()) return $this->errorJson('当前请求不合法！');
        $post = $request->post();
        if(!$this->sceneValidate($post, 'add')) return $this->errorJson($this->msg);
        try {
            $this->model->transaction(function () use ($post, &$save, &$save2, &$save3, &$save4)
            {
                $admin  = json_decode($post['admin'],true);
                $owners = json_decode($post['owners'],true);
                $bank   = json_decode($post['bank'],true);
                if (empty($admin['password'])) $admin['password'] = '123456';
                $admin['password'] = password($admin['password']);
                $admin['store_id'] = $owners['store_id'] = $bank['store_id'] =  $this->model->id;
                $save  = $this->model->save($post);
                $save2 = $this->model->admin()->save($admin);
                $save3 = $this->model->owners()->save($owners);
                $save4 = $this->model->bank()->save($bank);
            });
        } catch(\Exception $e) {
            return $this->errorJson('新增失败:' . $e->getMessage());
        }
        if(!$save || !$save2 || !$save3 || !$save4) return $this->errorJson('新增失败');
        return $this->successJson('新增成功');
    }

}